package com.sharelogindemo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 1 on 2017/9/28.
 */

public class Utils {
    public static final int COUNTRY_CHINA_CODE = 86;
    public static final int COUNTRY_HONGKONG_CODE = 852;
    public static final int COUNTRY_MACAU_CODE = 853;
    public static final int COUNTRY_TAIWAN_CODE = 886;
    /**
     * 判断程序是否可用
     * @param context
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        try {
            final PackageManager packageManager = context.getPackageManager();
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals(packageName)) {
                        return true;
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
	 * 判断是否为4位验证码
	 */
    public static boolean isCodeNumber(String code) {
        if(Pattern.matches("^[0-9]{4}", code)){
            return true;
        }
        return false;
    }


    /*
     * 判断是否为手机号码
     */
    public static boolean isPhoneNumberValid(String phoneNumber, int countryCode, boolean isLogin) {

        Pattern p;
        Matcher m;

        if(isLogin) {
            return Pattern.compile("^1\\d{10}$").matcher(phoneNumber).matches()
                    || Pattern.compile("^[1-9]\\d{7}$").matcher(phoneNumber).matches()
                    || Pattern.compile("^[1-9]\\d{7}$").matcher(phoneNumber).matches()
                    || Pattern.compile("^09\\d{8}$").matcher(phoneNumber).matches();
        }else {
            switch (countryCode) {
                case COUNTRY_CHINA_CODE:
                    p = Pattern.compile("^1\\d{10}$");
                    break;

                case COUNTRY_HONGKONG_CODE:
                    p = Pattern.compile("^[1-9]\\d{7}$");
                    break;

                case COUNTRY_MACAU_CODE:
                    p = Pattern.compile("^[1-9]\\d{7}$");
                    break;

                case COUNTRY_TAIWAN_CODE:
                    p = Pattern.compile("^09\\d{8}$");
                    break;

                default:
                    p = Pattern.compile("^1\\d{10}$");
                    break;
            }
            m = p.matcher(phoneNumber);

            return m.matches();
        }
    }

    /*
	 * 判断密码是否为6-20位数
	 */
    public static boolean isPasswordNumber(String password) {
        if(Pattern.matches("^[0-9a-zA-Z]{6,20}", password)){
            return true;
        }
        return false;
    }

    /**
     * 判断字符是否为空
     * @param str
     * @return
     */
    public static boolean isNullOrEmpty(String str) {
        if (str == null || str.equals("")) {
            return true;
        } else {
            return false;
        }
    }

    /*
	 * 判断密码是否为数字和字母
	 */
    public static boolean isPasswordNumber1(String password, EditText editText) {
        try {
            if(Pattern.matches("^[A-Za-z0-9]+", password) || isNullOrEmpty(password)){
                return true;
            }else {
                String mPassword = password.substring(0, password.length() - 1);
                editText.setText(mPassword);
                editText.setSelection(mPassword.length());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static void startActivity(Context context,Class<?> activityName) {
        Intent intent = new Intent(context, activityName);
        context.startActivity(intent);
    }

    /*
	 * 跳出输入框
	 */
    public static void setSelection(final Context context, final EditText editText, final boolean isSupport) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                editText.requestFocus();
                editText.setSingleLine();
                editText.setFocusableInTouchMode(true);
                editText.setSelection(editText.getText().toString().length());
                InputMethodManager inputManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(editText, 0);
                if(!isSupport) {
                    editText.addTextChangedListener(new EditTextChangeListener(context, editText));
                }
            }
        }, 100);
    }

    public static class EditTextChangeListener implements TextWatcher {

        private EditText mEditText;
        private Context mContext;
        //输入表情前的光标位置
        private int cursorPos;
        //输入表情前EditText中的文本
        private String inputAfterText;
        //是否重置了EditText的内容
        private boolean resetText;

        public EditTextChangeListener(Context context, EditText editText) {
            this.mContext = context;
            this.mEditText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!resetText) {
                cursorPos = mEditText.getSelectionEnd();
                // 这里用s.toString()而不直接用s是因为如果用s，
                // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                // inputAfterText也就改变了，那么表情过滤就失败了
                inputAfterText= s.toString();
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!resetText) {
                if (count >= 2) {//表情符号的字符长度最小为2
                    try {
                        CharSequence input = s.subSequence(cursorPos, cursorPos + count);
                        if (containsEmoji(input.toString())) {
                            resetText = true;
                            ToastUtil.showToast(mContext, "不支持输入Emoji表情符号");
                            //是表情符号就将文本还原为输入表情符号之前的内容
                            mEditText.setText(inputAfterText);
                            CharSequence text = mEditText.getText();
                            if (text instanceof Spannable) {
                                Spannable spanText = (Spannable) text;
                                Selection.setSelection(spanText, text.length());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                resetText = false;
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * 检测是否有emoji表情
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    /** 加载数据对话框 */
    private static Dialog mLoadingDialog;
    private static Dialog mLoginningDialog;
    private static ProgressBar login_progress;
    private static TextView login_text;

    /**
     * 显示加载对话框
     * @param context 上下文
     * @param cancelable 对话框是否可以取消
     */
    public static void showDialogForLoginning(Context context, boolean cancelable) {
        try {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_loginning_dialog, null);
            login_progress = (ProgressBar) view.findViewById(R.id.login_progress);
            login_progress.setVisibility(View.VISIBLE);
            login_text = (TextView) view.findViewById(R.id.login_text);
            login_text.setVisibility(View.GONE);
            mLoginningDialog = new Dialog(context, R.style.normal_dialog);
            mLoginningDialog.setCancelable(true);
            mLoginningDialog.setCanceledOnTouchOutside(true);
            mLoginningDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            mLoginningDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭加载对话框
     */
    public static void hideDialogForLoginningg(final Activity activity, String notifition, boolean isLogin) {
        if(mLoginningDialog != null && mLoginningDialog.isShowing()) {
            try {
                if(isLogin) {
                    if(login_progress != null) {
                        login_progress.setVisibility(View.GONE);
                    }
                    if(login_text != null) {
                        if(!Utils.isNullOrEmpty(notifition)) {
                            login_text.setText(notifition);
                        }
                        login_text.setVisibility(View.VISIBLE);
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mLoginningDialog.dismiss();
                            mLoginningDialog.cancel();
                            activity.finish();
                        }
                    }, 1000);
                }else {
                    mLoginningDialog.dismiss();
                    mLoginningDialog.cancel();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
